package com.xiaoze.transform;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * TransformBase
 *
 * @author Lin Zemin
 * @date 2021-12-29
 */
public class TransformBase {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        String path = System.getProperty("user.dir") + "\\src\\main\\resources\\sensor.txt";
        DataStreamSource<String> inputStream = env.readTextFile(path);

        // 1、map把String转换成长度输出
        SingleOutputStreamOperator<Integer> map = inputStream.map((MapFunction<String, Integer>) String::length);

        // 2、flatMap 按照规则切分
        SingleOutputStreamOperator<String> flatMap = inputStream.flatMap((FlatMapFunction<String, String>) (s, collector) -> {
            String[] strArr = s.split(",");
            for(String str : strArr) {
                collector.collect(str);
            }
        }).returns(Types.STRING);

        // 3、filter 筛选过滤
        SingleOutputStreamOperator<String> filter = inputStream.filter((FilterFunction<String>) s -> s.startsWith("s"));

        map.print();
        flatMap.print();
        filter.print();

        env.execute();

    }

}
